import fs from 'fs/promises'
import path from 'path'
import { fileURLToPath } from 'url'
import YAML from 'yaml'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const configRoot = path.resolve(__dirname, '..', 'config')

let snapshot = null
const watchers = new Set()

export async function loadConfigSnapshot () {
  const entries = await fs.readdir(configRoot)
  const cfg = {}
  for (const file of entries) {
    const full = path.join(configRoot, file)
    if (file.endsWith('.js')) {
      const mod = await import(full)
      Object.assign(cfg, mod?.default ?? mod?.cfg ?? {})
    } else if (file.endsWith('.json')) {
      try {
        const raw = await fs.readFile(full, 'utf-8')
        Object.assign(cfg, JSON.parse(raw))
      } catch {}
    } else if (file.endsWith('.yaml') || file.endsWith('.yml')) {
      try {
        const raw = await fs.readFile(full, 'utf-8')
        Object.assign(cfg, YAML.parse(raw))
      } catch {}
    }
  }
  snapshot = Object.freeze(cfg)
  return snapshot
}

export function getConfigSnapshot () {
  return snapshot
}

export async function watchConfig (onChange) {
  if (typeof onChange === 'function') watchers.add(onChange)
  const watcher = fs.watch(configRoot, { persistent: false }, async () => {
    await loadConfigSnapshot()
    for (const fn of watchers) try { fn(snapshot) } catch {}
  })
  return () => { try { watcher.close() } catch {} }
}

await loadConfigSnapshot()

export default { loadConfigSnapshot, getConfigSnapshot, watchConfig }